package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"docker-monitor/internal/api"
	"docker-monitor/internal/docker"
	"docker-monitor/internal/mcp/adapters"
	"docker-monitor/internal/web"
)

func main() {
	// Parse command line arguments
	port := flag.String("port", "8080", "Port to serve on")
	mcpPort := flag.String("mcpport", "8081", "Port for MCP server")
	flag.Parse()

	// Create context for graceful shutdown
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Initialize Docker service
	dockerService, err := docker.NewDockerService()
	if err != nil {
		log.Fatalf("Failed to initialize Docker service: %v", err)
	}
	defer dockerService.Close()

	// Create router
	router := api.NewRouter(dockerService)
	
	// Add web UI routes
	web.AddRoutes(router)

	// Create HTTP server
	httpServer := &http.Server{
		Addr:    ":" + *port,
		Handler: router,
	}

	// Start HTTP server
	go func() {
		log.Printf("Starting server on port %s", *port)
		if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()

	// Start MCP server
	adapters.MCPIntegration(ctx, cancel, *mcpPort)

	// Wait for interrupt signal to gracefully shutdown the server
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	log.Println("Shutting down server...")
	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer shutdownCancel()

	// Cancel the main context to signal all services to shutdown
	cancel()

	if err := httpServer.Shutdown(shutdownCtx); err != nil {
		log.Fatalf("HTTP server forced to shutdown: %v", err)
	}

	log.Println("Server exited")
}